const fs = require("fs");
const path = require("path");

const outputData = [];

for (let i = 1; i <= 20; i++) {
  const fileName = `data${String(i).padStart(4, "0")}.csv`;
  const filePath = path.join(__dirname, "csv", fileName);

  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      console.error(`读取文件 ${fileName} 失败:`, err);
      return;
    }

    const lines = data.split("\n");
    if (lines.length >= 2) {
      const secondLine = lines[1].split(",");
      const newLine = [secondLine[1], secondLine[2], secondLine[3]].join(",");
      outputData.push(newLine);
    }

    // 当所有文件都处理完毕后，写入输出文件
    if (outputData.length === 20) {
      const outputFilePath = path.join(__dirname, `output1.csv`);
      fs.writeFile(outputFilePath, outputData.join("\n") + "\n", "utf8", (err) => {
        if (err) {
          console.error(`写入文件 ${outputFilePath} 失败:`, err);
        } else {
          console.log(`数据已成功写入 ${outputFilePath}`);
        }
      });
    }
  });
}
